package chapter05

object Test12_MyWhile {
  def main(args: Array[String]): Unit = {
    var n = 10
    //1
    while (n >= 1) {
      println("n=" + n)
      n -= 1
    }
    println("=========================================")

    //2. 用闭包实现一个函数，将代码块作为参数传入。
    def myWhile(condition: => Boolean): (=> Unit) => Unit = {
      //内层函数需要循环调用
      def loop(op: => Unit) = {
        if (condition) {
          op
          myWhile(condition)(op)
        }
      }

      loop
    }

    n = 10
    myWhile(n >= 1)(
      {
        println("n=" + n)
        n -= 1
      }
    )
    println("=========================================")

    //3. 用匿名函数进行实现
    def myWhile2(condition: => Boolean): (=> Unit) => Unit = {
      op => {
        if (condition) {
          op
          myWhile2(condition)(op)
        }
      }
    }

    n = 10
    myWhile2(n >= 1)(
      {
        println("n=" + n)
        n -= 1
      }
    )
    println("=========================================")

    //4. 使用柯里化实现
    def myWhile3(condition: => Boolean)(op: => Unit): Unit = {
      if (condition) {
        op
        myWhile3(condition)(op)
      }
    }

    myWhile3(n >= 1)(
      {
        println("n=" + n)
        n -= 1
      }
    )

  }

}
